//
//  PCDClientOCRH5Plugin.m
//  PCDBankSix
//
//  Created by Jason Tao on 2022/3/2.
//

#import "PCDClientOCRH5Plugin.h"
#import <ExBankCardSDK/ExBankCardSDK.h>

@interface PCDClientOCRH5Plugin()

@property (nonatomic, strong) NSString *strCallback;
@property (nonatomic, strong) NSString *strCallfailback;

@end

@implementation PCDClientOCRH5Plugin
//截取身份证的出生日期并转换为日期格式
-(NSString *)subsIDStrToDate:(NSString *)str{
    NSMutableString *result = [NSMutableString stringWithCapacity:0];
    
    NSString *dateStr = [str substringWithRange:NSMakeRange(6, 8)];
    NSString  *year = [dateStr substringWithRange:NSMakeRange(0, 4)];
    NSString  *month = [dateStr substringWithRange:NSMakeRange(4, 2)];
    NSString  *day = [dateStr substringWithRange:NSMakeRange(6,2)];
    
    [result appendString:year];
    [result appendString:@"-"];
    [result appendString:month];
    [result appendString:@"-"];
    [result appendString:day];
    
    return result;
}
- (void)handler:(id)data andContext:(PCDContext *)context ResponseCallback:(WVJBResponseCallback )responseCallback
{
    NSDictionary *dict = (NSDictionary *)data;
    
    NSString *ocrType = [NSString stringWithFormat:@"%@", dict[@"type"]];
    self.strCallback = dict[@"success"];
    self.strCallfailback = dict[@"fail"];
    self.bsContext = context;
    
    PCDBankWebViewController *vc =  self.bsContext.viewController;
    
    __weak typeof(self) tempSelf = self;
    if ([ocrType isEqualToString:@"1"]||[ocrType isEqualToString:@"2"]) {
        [EXOCRCardEngineManager initEngine];
        BOOL bShouldFront = NO;
        if ([ocrType isEqualToString:@"1"]) {
            bShouldFront = YES;
        } else {
            bShouldFront = NO;
        }
        
        EXOCRIDCardRecoManager *manager = [EXOCRIDCardRecoManager sharedManager:vc];
        [manager setDisplayLogo:NO];
        [manager setCustomScanView:nil];
        [manager displayScanViewControllerByPresent:YES];

        __weak typeof(self) weakSelf = self;
        [manager recoIDCardFromStreamWithSide:bShouldFront OnCompleted:^(int statusCode, EXOCRIDCardInfo *idInfo) {
            if (idInfo.type == 1) {
                NSData * frontFullImgData = [weakSelf compressOriginalImage:idInfo.frontFullImg toMaxDataSizeKBytes:100 * 1024];
                NSData * faceImgData = [weakSelf compressOriginalImage:idInfo.faceImg toMaxDataSizeKBytes:100 * 1024];
                NSString * frontFullImgBase64Str = [frontFullImgData base64EncodedStringWithOptions:0];
                NSString * faceImgBase64Str = [faceImgData base64EncodedStringWithOptions:0];
                
                NSDictionary *params = @{@"mName":idInfo.name,
                                         @"mSex":idInfo.gender,
                                         @"mNation":idInfo.nation,
                                         @"mBirth":idInfo.birth,
                                         @"mAddress":idInfo.address,
                                         @"mCardNum":idInfo.code,
                                         @"mBase64FrontIMG":frontFullImgBase64Str,
                                         @"mBase64FaceIMG":faceImgBase64Str};
                evaluateJavaScriptOnMainThread(weakSelf, weakSelf.strCallback, [params JSONRepresentation]);
            }else {
                NSData * backImgData = UIImageJPEGRepresentation(idInfo.backFullImg, 0.5);
                
                NSString * backImgBase64Str = [backImgData base64EncodedStringWithOptions:0];
                
                NSDictionary *params = @{@"mOffice":idInfo.issue,
                                         @"mValidDate":idInfo.valid,
                                         @"mBase64BackIMG":backImgBase64Str};
                evaluateJavaScriptOnMainThread(weakSelf, weakSelf.strCallback, [params JSONRepresentation]);
            }
        } OnCanceled:^(int statusCode) {
        } OnFailed:^(int statusCode, UIImage *recoImg) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"识别失败，请重试" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                evaluateJavaScriptOnMainThread(weakSelf, weakSelf.strCallfailback, @"");
            }];
            [alertVC addAction:action];
            [vc presentViewController:alertVC animated:YES completion:nil];
        }];
        
        
    }else if ([ocrType isEqualToString:@"3"]){ //银行卡
        __weak __typeof__(self) weakSelf = self;
        EXOCRBankRecoManager *manager = [EXOCRBankRecoManager sharedManager:vc];
        [manager setDisplayLogo:NO];
        [manager setScanTips:@"请将银行卡正面放入框内"];
        [manager recoBankFromStreamOnCompleted:^(int statusCode, EXOCRBankCardInfo *bankInfo) {
            NSData * frontFullImgData = [self compressOriginalImage:bankInfo.fullImg toMaxDataSizeKBytes:100 * 1024];
            NSString * frontFullImgBase64Str = [frontFullImgData base64EncodedStringWithOptions:0];
            
            NSDictionary *params = @{@"mBankName":bankInfo.bankName,
                                     @"mCardName":bankInfo.cardName,
                                     @"mCardType":bankInfo.cardType,
                                     @"mCardNo":bankInfo.cardNum,
                                     @"mCardValid":bankInfo.validDate,
                                     @"mBase64IMG":frontFullImgBase64Str};
            evaluateJavaScriptOnMainThread(weakSelf, weakSelf.strCallback, [params JSONRepresentation]);
        } OnCanceled:^(int statusCode) {
        } OnFailed:^(int statusCode, UIImage *failImg) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"识别失败，请重试" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                evaluateJavaScriptOnMainThread(weakSelf, weakSelf.strCallfailback, @"");
            }];
            [alertVC addAction:action];
            [vc presentViewController:alertVC animated:YES completion:nil];
        }];
        
        
    }else if ([ocrType isEqualToString:@"4"]){
        __weak __typeof__(self) weakSelf = self;
//        //营业执照
//        EXOCRQuadCaptureManager *manager = [EXOCRQuadCaptureManager sharedManager:vc];
//        [manager setDisplayLogo:NO];
//        [manager setSkipPreview:YES];
//        //初始化
//        [EXOCRCardEngineManager initEngine];
//        [manager captureQuadCardWithCardType:EXOCRCaptureCardTypeDefault OnCompleted:^(int statusCode, EXOCRQuadCardInfo *quadInfo) {
//            NSData * imageData = [weakSelf compressOriginalImage:quadInfo.cardImg toMaxDataSizeKBytes:100 * 1024];
//            NSString *imageBase64Str = [imageData base64EncodedStringWithOptions:0];
//            NSDictionary *params = @{@"mBase64CaptureIMG":imageBase64Str};
//            evaluateJavaScriptOnMainThread(weakSelf, weakSelf.strCallback, [params JSONRepresentation]);
//        } OnCanceled:nil
//        OnFailed:^(int statusCode, UIImage *recoImg) {
//            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"识别失败，请重试" preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                evaluateJavaScriptOnMainThread(weakSelf, weakSelf.strCallfailback, @"");
//            }];
//            [alertVC addAction:action];
//            [vc presentViewController:alertVC animated:YES completion:nil];
//        }];
        
        //营业执照
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
            authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先去设置中开启相机权限" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAct = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:cancelAct];
            UIAlertAction *settingAct = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication]canOpenURL:url]) {
                    [[UIApplication sharedApplication]openURL:url];
                }
            }];
            [alertController addAction:settingAct];
            [vc.navigationController presentViewController:alertController animated:YES completion:nil];
            
            return;
        }
        [self addPicEvent:nil type:UIImagePickerControllerSourceTypeCamera responseBlock: ^(id responseData)
         {
             
         }];
    }
}

- (void) addPicEvent:(NSDictionary *)parma type:(UIImagePickerControllerSourceType)picType  responseBlock:(WVJBResponseCallback)responseCallback {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        PCDLog(@"不支持相机");
        return;
    }
    
    UIImagePickerControllerSourceType sourceType = picType;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = sourceType;
    picker.completionBlock = ^(UIImagePickerController *pickerController, NSDictionary *info){
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData * imageData = [self compressOriginalImage:image toMaxDataSizeKBytes:100 * 1024];
        NSString *imageBase64Str = [imageData base64EncodedStringWithOptions:0];
        NSDictionary *params = @{@"mBase64CaptureIMG":imageBase64Str};
        
        evaluateJavaScriptOnMainThread(self, self.strCallback, [params JSONRepresentation]);
        [pickerController dismissViewControllerAnimated:YES completion:NULL];
    };
    
    picker.cancelBlock = ^(UIImagePickerController *picker){
        [picker dismissViewControllerAnimated:YES completion:NULL];
    };
    
    [self.bsContext.viewController presentViewController:picker animated:YES completion:NULL];
}

/*图片压缩
 1.UIImageJPEGRepresentation压缩图片,若图片过大,则无法压缩到100K以下
 2.比例缩小的方式压缩缩略图则图片会模糊不清
 3.所以先使用UIImageJPEGRepresentation压图片到足够小,再比例缩小的方式缩图片
 最大程度保持图片识别度
 */
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)maxLength{
    //首先判断原图大小是否在要求内，如果满足要求则不进行压缩，over
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return data;
    //压处理，
    //这里 压缩比 采用二分法进行处理，6次二分后的最小压缩比是0.015625，已经够小了
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) {
        return data;
    }
    
    //缩处理
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //获取处理后图片的大小
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    return data;
}

- (void)dealloc {
    [EXOCRCardEngineManager finishEngine];
}

@end
